package com.winterwar.dao.hibernate;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.winterwar.base.User;
import com.winterwar.dao.UserDAO;

public class UserDAOHibernate extends HibernateDaoSupport implements UserDAO {
	private Log log = LogFactory.getLog(UserDAO.class);

	public User get(Integer userID) {
		return (User) getHibernateTemplate().get(User.class, userID);
	}

	public List getAll() {
		return getHibernateTemplate().find("from User order by lastName");
	}

	public void remove(Integer userID) {
		Object user = getHibernateTemplate().load(User.class, userID);
		getHibernateTemplate().delete(user);
		getHibernateTemplate().flush();
	}

	public void save(User user) {
		getHibernateTemplate().saveOrUpdate(user);
		getHibernateTemplate().flush();
		if(log.isDebugEnabled()){
			log.debug("User ID set to: " + user.getUserID());
		}
	}

	public List getLogin(String username, String password) {
		return getHibernateTemplate().find("from User where username = '"+username+"' and password = '"+password+"'");
	}

	public User getByUserName(String username) {
		List users = getHibernateTemplate().find("from User where username = '" + username + "'");
		if(users.size() > 0){
			return (User) users.get(0);
		} else return null;
	}
	
	public User getByFirstAndLast(String first, String last){
		List users = getHibernateTemplate().find("from User where firstName = '" + first+ "' and lastName = '" + last.replace("'", "''") + "'");
		if(users.size() > 0){
			return (User) users.get(0);
		} else return null;
	}

	@Override
	public List getByEmail(String eMail) {
		return getHibernateTemplate().find("from User where email = '"+eMail+"' order by lastName");
	}
}
